"""
FileName：flask_for_mock_pay.py
Description：
Author：gaojiahui
Time：2025/8/16 9:58
Website：https://gitee.com/gao-jiahui
"""
import threading
import time

from flask import Flask, request, jsonify

"""使用Flask搭建Mock支付网关"""

app = Flask(__name__)

# 存储回调记录
callback_records = {}


@app.route('/mock-pay/create', methods=['POST'])
def create_payment():
    """创建模拟支付订单"""
    data = request.json
    order_id = data['order_id']
    amount = data['amount']

    # 生成模拟支付订单
    payment_id = f"PAY-{time.time_ns()}"
    callback_records[payment_id] = {
        "order_id": order_id,
        "status": "PENDING",
        "callbacks": []
    }

    # 启动异步回调线程
    threading.Thread(target=simulate_payment_process, args=(payment_id,)).start()

    return jsonify({
        "code": 0,
        "data": {
            "payment_id": payment_id,
            "pay_url": f"http://mock-pay-gateway/pay/{payment_id}"
        }
    })


@app.route('/mock-pay/callback', methods=['POST'])
def handle_callback():
    """处理支付回调（Pig系统调用）"""
    callback_data = request.json
    payment_id = callback_data['payment_id']

    if payment_id in callback_records:
        callback_records[payment_id]['callbacks'].append({
            "time": time.strftime("%Y-%m-%d %H:%M:%S"),
            "data": callback_data
        })
        return jsonify({"code": 0, "msg": "回调接收成功"})

    return jsonify({"code": 404, "msg": "支付订单不存在"}), 404

def simulate_payment_process(payment_id):
    """模拟支付流程（后台线程）"""
    # 等待5-15秒模拟支付过程
    time.sleep(5 + (hash(payment_id) % 10))

    # 随机决定支付结果
    is_success = hash(payment_id) % 5 != 0  # 80%成功率

    callback_records[payment_id]['status'] = 'PAID' if is_success else 'FAILED'

    # 记录回调信息
    callback_records[payment_id]['result'] = {
        "status": "SUCCESS" if is_success else "FAILURE",
        "payment_id": payment_id,
        "completed_at": time.strftime("%Y-%m-%d %H:%M:%S")
    }

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000,debug=True)